package com.jams.goodox.activity.login;

import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.entity.RegisterBean;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.LoginService;
import com.jams.goodox.utils.StatusBarCompat;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.widget.EditTextWithDel;

import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 注册填写信息页
 *
 * api/member/register
 * @author HP
 */
public class RegistActivity extends BaseActivity {

    private static final String TAG = RegistActivity.class.getSimpleName();
    @Bind(R.id.edit_userPass)
    EditTextWithDel edit_userPass;
    @Bind(R.id.edit_userPass2)
    EditTextWithDel edit_userPass2;

    @Bind(R.id.img_login_seePass)
    ImageView img_login_seePass;

    @Bind(R.id.img_login_seePass2)
    ImageView img_login_seePass2;


    @Bind(R.id.tx_register)
    TextView tx_register;


    private static final String TEL_LENGTH = "请输入11位手机号";
    private static final String CODE_NOT_HAVE = "请输入验证码";
    private static final String CODE_LENGTH = "验证码错误";
    private static final String PASS_NOT_HAVE = "请输入6-12位密码";
    private static final String PASS_FORMAT = "密码请使用6-12位英文或数字";

    private static final String NOT_AGREEMENT = "请勾选阅读并勾选用户协议";

    private boolean isPassShow = false;//标示密码是否可见
    private boolean isPassShow2 = false;//标示密码是否可见
    private boolean isAgreed = true;

    private static final int Time_Close = 60;//倒计时持续多少秒
    private String mobile;//手机号
    private String smsVerCode;//验证码


    @Override
    protected int getLayoutId() {
        return R.layout.activity_regist_first;
    }

    @Override
    protected void init() {
        StyleUtil.titleBackKey(this, "注册");
        StatusBarCompat.compat(this, ContextCompat.getColor(this, R.color.main_theme));//沉侵式头部
        mobile = getIntent().getStringExtra("mobile");
        smsVerCode = getIntent().getStringExtra("smsVerCode");

    }

    @OnClick({R.id.ler_back,  R.id.tx_register,R.id.img_login_seePass,R.id.img_login_seePass2})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tx_register:
                register();
                break;

            case R.id.img_login_seePass:
                isPassShow = !isPassShow;
                if (isPassShow) {
                    img_login_seePass.setImageResource(R.mipmap.see_pass_icon);
                    edit_userPass.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    img_login_seePass.setImageResource(R.mipmap.not_see_pass_icon);
                    edit_userPass.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                edit_userPass.setSelection(edit_userPass.length());
                break;


            case R.id.img_login_seePass2:
                isPassShow2 = !isPassShow2;
                if (isPassShow2) {
                    img_login_seePass2.setImageResource(R.mipmap.see_pass_icon);
                    edit_userPass2.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    img_login_seePass2.setImageResource(R.mipmap.not_see_pass_icon);
                    edit_userPass2.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                edit_userPass2.setSelection(edit_userPass2.length());
                break;

//            case R.id.img_agreement:
//                isAgreed = !isAgreed;
//                if (isAgreed) imgAgreement.setImageResource(R.mipmap.agreement_choose);
//                else imgAgreement.setImageResource(R.mipmap.agreement_no);
//                break;
//            case R.id.tx_user_agreement:
//                Intent in = new Intent(this, SimpleHtmlActivity.class);
//                in.putExtra(SimpleHtmlActivity.URL, H5UrlConstants.H5_Agreement);
//                in.putExtra(SimpleHtmlActivity.TITLE, "用户协议");
//                qStartActivity(in);
//                break;
        }
    }



    /**
     * 注册
     */
    private void register() {

        String pwd = edit_userPass.getText().toString().trim();
        if (TextUtils.isEmpty(edit_userPass.getText())) {
            ToastUtil.showShort(this, PASS_NOT_HAVE);
            return;
        }


        if (pwd.length() < 6 && pwd.length() > 18) {
            ToastUtil.showShort(this, PASS_NOT_HAVE);
            return;
        }

        if(TextUtils.isEmpty( edit_userPass2.getText())){
            ToastUtil.showShort(this, "请再次确认密码");
            return;
        }

        String pwd2 = edit_userPass2.getText().toString().trim();
        if(!pwd2.equals(pwd)){
            ToastUtil.showShort(this, "两次密码不一致");
            return;
        }

        clearMap();
        StringBuilder pData = new StringBuilder();
        pData.append("password:" + pwd2)
                .append(",mobile:" + mobile)
                .append(",smsVerCode:" + smsVerCode);

        params.put("requestData", "{" + pData.toString() + "}");

        String strEntity = gson.toJson(params);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"),strEntity);

        showLoading();

        Call<ResponseBody> example = createCallService(LoginService.class).registerUser(body);

        example.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                misLoading();
                try {
                    String data = response.body().string();
                    Log.d(TAG, "data = " + data);

                    JSONObject jsonObject = new JSONObject(data);

                    if(200 == jsonObject.getInt("code")){
                        JSONObject object = new JSONObject(jsonObject.getString("responseData"));
                        SePref.setId(object.getInt("id"));
                        Intent intent = new Intent(RegistActivity.this, RoleChooseActivity.class);
                        startActivity(intent);
                        finish();

                    }else {
                        if(jsonObject.has("error")){
                            ToastUtil.show("error:" + jsonObject.getString("error") );
                        }else {
                            ToastUtil.show("网络异常！" );
                        }
                    }
                } catch (Exception e) {
                    ToastUtil.show("Exception:" + e.getMessage());
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                misLoading();
                Log.d(TAG,"onFailure = " + t.getMessage());
            }
        });

    }

}
